package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class GatewayFilters implements GatewayFilter,Override {

    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> whites = ignoreWhiteConfig.getWhites();

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }

        // 判断 token 是否为空
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        if (StringUtils.isNotBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token 不能为空", HttpStatus.UNAUTHORIZED);
        }

        // 判断 token 是否合法
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"token 不合法");
        }

        // 判断 token 是否过期
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token 已过期");
        }

        // 每次访问后台gateway进行拦截10分钟内访问后台自动续期Token到15分钟（3分）
        Long expire = redisTemplate.getExpire(TokenConstants.LOGIN_TOKEN_KEY + userKey, TimeUnit.MINUTES);
        if (expire>5){
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY+userKey,15,TimeUnit.MINUTES);
        }else {
            return GatewayUtils.errorResponse(exchange,"10分钟内为登录,请重新登录");
        }

        return chain.filter(exchange);
    }


    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }


}
